import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class Flutter2JsByUrl extends StatefulWidget {
  const Flutter2JsByUrl({super.key});

  @override
  State<Flutter2JsByUrl> createState() => _Flutter2JsByUrlState();
}

class _Flutter2JsByUrlState extends State<Flutter2JsByUrl> {
  int progress = 0;
  late WebViewController controller;

  get _loadBtn => FilledButton(
    onPressed: () {
      controller.loadRequest(
        Uri.parse(
          'https://www.geekailab.com/io/flutter-trip/Flutter2JSByUrl.html?name=xxx',
        ),
      );
    },
    child: Text('加载H5', style: TextStyle(color: Colors.white)),
  );

  @override
  void initState() {
    super.initState();
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (progress) {
            setState(() {
              this.progress = progress;
            });
          },
        ),
      );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter向JS传递数据-通过URL方式'),
        actions: [_loadBtn],
      ),
      body: Stack(
        children: [
          WebViewWidget(controller: controller),
          Positioned(child: Text('加载进度: $progress')),
        ],
      ),
    );
  }
}
